package com.spark.market.service.manager;

import com.spark.market.api.dto.ItemInfo;
import com.spark.market.common.utils.AssertUtils;
import com.spark.market.dal.entity.PromoDo;
import com.spark.market.dal.model.PromoModel;
import com.spark.market.dal.repository.PromoRepository;
import com.spark.market.service.ItemQueryCoreService;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Component
public class PromoManager {
    @Resource
    PromoRepository promoRepository;
    @Resource
    ItemQueryCoreService itemQueryCoreService;
    @Resource
    RedisTemplate<Object, Object> redisTemplate;

    public PromoModel queryPromoByItemId(Integer itemId) {
        AssertUtils.isNotNull(itemId, "itemId is null");
        PromoDo promoDo = promoRepository.selectPromoByItemId(itemId);
        //校验活动状态
        PromoModel promoModel = convertFromPromoModel(promoDo);
        if (promoModel == null){
            return null;
        }
        if (promoModel.getStartDate().isAfterNow()){
            promoModel.setStatus(1);
        }else if (promoModel.getEndDate().isBeforeNow()){
            promoModel.setStatus(3);
        }else{
            promoModel.setStatus(2);
        }
        return promoModel;
    }

    public PromoModel convertFromPromoModel(PromoDo promoDo){
        if (promoDo == null){
            return null;
        }
        PromoModel promoModel = new PromoModel();
        BeanUtils.copyProperties(promoDo, promoModel);
        promoModel.setPromoItemPrice(BigDecimal.valueOf(promoDo.getPromoItemPrice()));
        promoModel.setStartDate(new DateTime(promoDo.getStartDate()));
        promoModel.setEndDate(new DateTime(promoDo.getEndDate()));
        return promoModel;
    }

    public void queryItemModel(Integer itemId) {
        PromoModel promoModel = this.queryPromoByItemId(itemId);
        if (promoModel == null || promoModel.getItemId().intValue() == 0){
            return;
        }
        ItemInfo itemDetail = itemQueryCoreService.getItemDetail(promoModel.getItemId());
        //秒杀商品库存入缓存
        redisTemplate.opsForValue().set("promo_item_stock_" + itemDetail.getId(), itemDetail.getStock());
        //即哪个秒杀大闸设置到redis中
        redisTemplate.opsForValue().set("promo_door_count_" + itemDetail.getPromoId(), itemDetail.getStock().intValue() * 5);
    }
}
